// packageA/pages/dataCollector/dataCollector.js
const app = getApp();
import CommonService from '../../../utils/service/commonService.js';
import Toast from '../../../miniprogram_npm/@vant/weapp/toast/toast';
const util = require('../../../utils/util');

Page({
  /**
   * 页面的初始数据
   */
  data: {
    //列表
    list:[],
    //页码
    page: 1,
    //是否无更多
    notMore: true,
    //无数据
    showNothing:false,
    //搜索词
		searchValue:'',
		searchValue2:'',
		//查询条件-仓库
		paramWarehouse: {
			id: -1,
			name: '所有仓库'
		},
		//查询条件-客户
		paramMember: {
			id: -1,
			name: '所有客户'
		},
    //状态筛选
    optionState:[
      {text: '所有状态', value: -1},
      {text: '未安装', value: 0},
			{text: '已安装', value: 1},
			{text: '返厂', value: 2},
			{text: '报废', value: 3}
    ],
    valueState: -1,
		//区分日期的标识
		currentField: null,
		//显示日历
    showDate: false,
    //开始时间
		startExpire: '开始日期',
		startAct: '开始日期',
		startLatest: '开始日期',
		//结束时间
		endExpire: '结束日期',
		endAct: '结束日期',
		endLatest: '结束日期',
		//最小值为6个月前，最大值用组件默认：6个月后
		minDate: util.countPrevDay(new Date(),186),
		//选择框
    showSelect:false,
    //选择数据
    selectList:[],
    //当前选择
    selectField:'',
    //选择框标题
    selectTitle:'',
    //显示选择搜索框
    showSelectSearch:false,
    //选择框搜索
    valueSearch: '',
		//数据看板
		dataSum: null	
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    //获取列表数据
		this.getList();	
  },

  //获取列表数据
  getList(){
    Toast.loading({
      duration: 0,
      forbidClick: true,
      message: '加载中...'
    });

    let param = {
      selectFields: ["id", "imei", "softwareVersion", "typeName", "manufactureDate", "iccid","createDate","warehouseId","warehouse","operationLog","shipmentDate","latestActivationDate","expirationDate","activationDate","state","remarks","outDate","initWarehouse"],
			sort: {
				id: -1
			},
			page: {
        page: this.data.page,
        pageSize: 10
      }
		}
		
		//查编码
    if(this.data.searchValue){
      param.imei = this.data.searchValue;
		}
		
		//查iccid
    if(this.data.searchValue2){
      param.iccid = this.data.searchValue2;
		}
		
		//查仓库
		if(this.data.paramWarehouse.id!=-1){
			param.initWarehouseId = this.data.paramWarehouse.id;
		}

		//状态筛选
		if(this.data.valueState!=-1){
			param.state = this.data.valueState;
		}

		//查客户
		if(this.data.paramMember.id!=-1){
			param.factoryId = this.data.paramMember.id;
		}

		//到期时间
		if(this.data.startExpire!='开始日期' && this.data.endExpire!='结束日期'){
			param.expirationDate={
				'>=': this.data.startExpire + ' 00:00:00',
				'<=': this.data.endExpire + ' 23:59:59',
			}
		}

		//激活时间
		if(this.data.startAct!='开始日期' && this.data.endAct!='结束日期'){
			param.activationDate={
				'>=': this.data.startAct + ' 00:00:00',
				'<=': this.data.endAct + ' 23:59:59',
			}
		}

		//最晚激活时间
		if(this.data.startLatest!='开始日期' && this.data.endLatest!='结束日期'){
			param.latestActivationDate={
				'>=': this.data.startLatest + ' 00:00:00',
				'<=': this.data.endLatest + ' 23:59:59',
			}
		}

    CommonService.findWarehouseImei(param).then(res => {
			console.log('模块数据');
			console.log(res);

      if(res.data.data && res.data.data.count) {	
				let result = res.data.data.result;

				this.setData({
          dataSum:{
						//总库存
						all: res.data.data.count || 0,
						//出库数量
						out: result.outCount || 0,
						//未出库数量
						notOut: result.unOutCount || 0,
						//到期设备数
						expire: result.expiredList.length || 0
					}
        })

				//模块列表
				let list = result.list;
				if(list && list.length){
					list.forEach(item => {
						//状态
						switch(item.state){
							case 0:
								item.self_state='未安装';
								item.self_stateClass='c-1';
								break;
							case 1:
								item.self_state='已安装';
								item.self_stateClass='c-2';
								break;
							case 2:
								item.self_state='返厂';
								item.self_stateClass='c-3';
								break;
							case 3:
								item.self_state='报废';
								item.self_stateClass='c-4';
								break;
							default:
								item.self_state='未安装';
								item.self_stateClass='c-1';
						}
					});
	
					this.setData({
						list: this.data.list.concat(list)
					})
					Toast.clear();
					
				}else{
					this.setData({
						notMore: false
					})
					if(this.data.page==1){
						this.setData({
							showNothing: true
						})
						Toast.clear();
					}else{
						Toast.fail('没有更多了');
					}
				}
      }else{
				this.setData({
					showNothing: true
				})
				Toast.clear();
			}
    }).catch((error) => {
      this.setData({
        showNothing: true
      })
      Toast.clear();
    })
  },

  //刷新列表和页码
  refreshListAndPage(){
    this.setData({
      list: [],
      page:1,
      notMore: true,
      showNothing: false
    })
    this.getList();
	},

	//跳转发货表单
	goToSend(){
		wx.navigateTo({
      url: "/packageA/pages/dataCollectorSend/dataCollectorSend"
    })
	},

  //获取搜索词
  onChangeSearch(e) {
    this.setData({
      searchValue: e.detail.value
    })
	},
  onChangeSearch2(e) {
    this.setData({
      searchValue2: e.detail.value
    })
  },

  //点击搜索
  onSearch(){
    this.refreshListAndPage();
  },

  //选择状态
  onChangeState({detail}) {
    this.setData({
      valueState: detail
    })
    this.refreshListAndPage();
	},
	
	//显示选择框
  onShowSelect(e){
    this.setData({
      selectList: []
    })

    let dataset=e.currentTarget.dataset;
    let field=dataset.field;

    this.setData({
      showSelect: true,
      selectField: field
    })

    //仓库
    if(field=='warehouse'){
      this.setData({
        selectTitle: '仓库',
        showSelectSearch: false
      })
      this.getWarehouseList();
		}
		
		//客户
    if(field=='depart'){
      this.setData({
        selectTitle: '客户',
        showSelectSearch: true
      })
      this.getDepartList();
    }
  },

  //隐藏选择框
  onCloseSelect(){
    this.setData({
      showSelect: false,
      valueSearch: '',
      disabled: false
    })
  },

  //确认选项
  onConfirmSelect(e){
    let selectField=this.data.selectField;
    let id=null,name=null,obj=null;

    //仓库
    if(selectField=='warehouse'){
      obj='paramWarehouse';
		}
		
		//客户
    if(selectField=='depart'){
      obj='paramMember';
    }

    if(id && name){
      this.setData({
        [id]:e.detail.value.id,
        [name]:e.detail.value.text
      })
    }

    if(obj){
      this.setData({
        [obj]:e.detail.value.obj
      })
    }

		this.onCloseSelect();
		this.refreshListAndPage();
  },

  //清除选项
  onCancelSelect(){
    let selectField=this.data.selectField;

    //仓库
    if(selectField=='warehouse'){
      this.setData({
        paramWarehouse: {
					id: -1,
					name: '所有仓库'
				},
      })
		}
		
		//客户
    if(selectField=='depart'){
      this.setData({
        paramMember: {
					id: -1,
					name: '所有客户'
				},
      })
    }

		this.onCloseSelect();
		this.refreshListAndPage();
  },

  //选择框搜索
  onChangeSelectVal(e){
    let selectField=this.data.selectField;

    this.setData({
      valueSearch: e.detail
    })

    //客户
    if(selectField=='depart'){
      this.getDepartList();
    }
  },

  //查询仓库
  getWarehouseList(){
    let param = {
      isAuth: true,
      className: 'warehouse',
      data: {
        searchAll: true,
        selectFields: ['id','name']
      }
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
	},

	//查询客户
  getDepartList(){
    let param = {
      isAuth: true,
      className: 'depart',
      data: {
				id:{">=":100000},
        searchAll: true,
        selectFields: ['id','name']
      }
		}
		
		if(this.data.valueSearch){
      param.data.name='%' + this.data.valueSearch + '%';
    }

    CommonService.goFindList(param).then(res=>{
      if(res.data.data && res.data.data.result && res.data.data.result.length){
        let result=res.data.data.result;
        let arr=[];
        result.forEach(item => {
          arr.push({
            text:item.name,
            id:item.id,
            obj:{
              id:item.id,
              name:item.name
            }
          });
        });

        this.setData({
          selectList: arr
        })
      }
    }).catch((error) => {
    })
	},

	//显示日历
  onShowDate({currentTarget}) {
		this.setData({
			currentField: currentTarget.dataset.field,
			showDate: true
		})
  },

  //隐藏日历
  onCloseDate() {
    this.setData({ 
      showDate: false 
    })
  },

  //确认日期
  onConfirmDate(event) {
		const [start,end] = event.detail;
		let currentField = this.data.currentField;

		//到期时间
		if(currentField=='timeExpire'){
			this.setData({
				startExpire: util.timeFormatDay(start),
				endExpire: util.timeFormatDay(end)
			})
		}

		//激活时间
		if(currentField=='timeAct'){
			this.setData({
				startAct: util.timeFormatDay(start),
				endAct: util.timeFormatDay(end)
			})
		}

		//最晚激活时间
		if(currentField=='timeLatest'){
			this.setData({
				startLatest: util.timeFormatDay(start),
				endLatest: util.timeFormatDay(end)
			})
		}

		//隐藏日历
		this.setData({
      showDate: false
		})

    //获取列表数据
		this.refreshListAndPage();
	},

	//清空日期条件
	onClearTime(){
		this.setData({
			startExpire: '开始日期',
			endExpire: '结束日期',
			startAct: '开始日期',
			endAct: '结束日期',
			startLatest: '开始日期',
			endLatest: '结束日期',
		})

		//获取列表数据
		this.refreshListAndPage();
	},

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if(this.data.notMore){
      this.setData({
        page: this.data.page + 1
      })
      this.getList();
    }
  }
})